import { useEffect, useMemo, useState } from "react";
import { Button, Card, Drawer, Form, Input, Space, Select } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import supplierService, { type PageListReq } from "@/api/services/base/supplierService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import type { Supplier } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";

const { TextArea } = Input;

export default function SupplierPage() {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		supplierCode: undefined,
		supplierName: undefined,
		status: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<Supplier[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<Supplier | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const supplierLevelOptions = useDictionary("supplier_level");
	const statusOptions = useDictionary("system_status");

	const columns: ColumnsType<Supplier> = [
		{
			title: "编码",
			width: 120,
			key: "supplierCode",
			dataIndex: "supplierCode",
		},
		{
			title: "名称",
			width: 120,
			key: "supplierName",
			dataIndex: "supplierName",
		},
		{
			title: "简称",
			width: 120,
			key: "supplierNick",
			dataIndex: "supplierNick",
		},
		{
			title: "英文名称",
			width: 120,
			key: "supplierEn",
			dataIndex: "supplierEn",
		},
		{
			title: "等级",
			width: 120,
			key: "supplierLevel",
			dataIndex: "supplierLevel",
			render: (_, record) => <TableDictTag dictCode="supplier_level" value={record.supplierLevel ?? ""} />,
		},
		{
			title: "评分",
			width: 120,
			key: "supplierScore",
			dataIndex: "supplierScore",
		},
		{
			title: "电话",
			width: 120,
			key: "tel",
			dataIndex: "tel",
		},
		{
			title: "联系人",
			width: 120,
			key: "contact",
			dataIndex: "contact",
		},
		{
			title: "是否启用",
			width: 120,
			key: "status",
			dataIndex: "status",
			render: (_, record) => <TableDictTag dictCode="system_status" value={record.status ?? ""} />,
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => (col.key ? String(col.key) : "")),
	);

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	const filteredColumns = useMemo(() => {
		return [...columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation")].sort(
			(a, b) => {
				const originalIndex = columns.findIndex((c) => c.key === a.key);
				const targetIndex = columns.findIndex((c) => c.key === b.key);
				return originalIndex - targetIndex;
			},
		);
	}, [selectedValues]);

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		supplierService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (supplier: Supplier) => {
		setEditingData(supplier);
		form.setFieldsValue(supplier);
		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (supplier: Supplier) => {
		setEditingData(supplier);
		form.setFieldsValue(supplier);
		setIsView(true);
		setDrawerVisible(true);
	};

	//提交表单数据
	const handleSubmit = async (values: Supplier) => {
		try {
			setLoading(true);
			if (editingData) {
				await supplierService.update({ ...values, id: editingData.id });
				toast.success("更新供应商成功");
			} else {
				await supplierService.add(values);
				toast.success("创建供应商成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`保存失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await supplierService.remove(selectedRowKeys);
			toast.success("删除供应商成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	return (
		<>
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="supplierCode" label="供应商编码">
						<Input placeholder="请输入供应商编码" allowClear />
					</Form.Item>
					<Form.Item name="supplierName" label="供应商名称">
						<Input placeholder="请输入供应商名称" allowClear />
					</Form.Item>
					<Form.Item name="status" label="状态">
						<Select options={statusOptions} allowClear style={{ width: 150 }} />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<div className="flex justify-between mb-4">
					<div className="flex gap-2">
						<Button type="primary" onClick={handleAdd}>
							新增
						</Button>
						<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
							删除
						</Button>
					</div>
					<TableToolbar
						onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="id"
					size={tableSize}
					scroll={{ x: "max-content", y: tableScrollY }}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={filteredColumns}
					dataSource={list}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑供应商" : "新增供应商"}
				width={480}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item
						name="supplierCode"
						label="供应商编码"
						rules={[
							{
								required: true,
								message: "请填写供应商编码",
							},
						]}
					>
						<Input placeholder="请输入供应商编码" allowClear />
					</Form.Item>
					<Form.Item
						name="supplierName"
						label="供应商名称"
						rules={[
							{
								required: true,
								message: "请填写供应商名称",
							},
						]}
					>
						<Input placeholder="请输入供应商名称" allowClear />
					</Form.Item>
					<Form.Item name="supplierNick" label="供应商简称">
						<Input placeholder="请输入供应商简称" allowClear />
					</Form.Item>
					<Form.Item name="supplierEn" label="供应商英文名称">
						<Input placeholder="请输入供应商英文名称" allowClear />
					</Form.Item>
					<Form.Item name="supplierDes" label="供应商简介">
						<TextArea />
					</Form.Item>
					<Form.Item name="supplierLevel" label="供应商等级" initialValue="B">
						<Select options={supplierLevelOptions} allowClear />
					</Form.Item>
					<Form.Item name="supplierScore" label="供应商评分">
						<Input placeholder="请输入供应商评分" allowClear />
					</Form.Item>
					<Form.Item name="address" label="供应商地址">
						<TextArea />
					</Form.Item>
					<Form.Item name="website" label="供应商官网地址">
						<Input placeholder="请输入供应商官网地址" allowClear />
					</Form.Item>
					<Form.Item name="email" label="供应商邮箱地址">
						<Input placeholder="请输入供应商邮箱地址" allowClear />
					</Form.Item>
					<Form.Item name="tel" label="供应商电话">
						<Input placeholder="请输入供应商电话" allowClear />
					</Form.Item>
					<Form.Item name="contact" label="联系人">
						<Input placeholder="请输入联系人" allowClear />
					</Form.Item>
					<Form.Item name="contactTel" label="联系人-电话">
						<Input placeholder="请输入联系人-电话" allowClear />
					</Form.Item>
					<Form.Item name="contactEmail" label="联系人-邮箱">
						<Input placeholder="请输入联系人-邮箱" allowClear />
					</Form.Item>
					<Form.Item name="creditCode" label="统一社会信用代码">
						<Input placeholder="请输入统一社会信用代码" allowClear />
					</Form.Item>
					<Form.Item
						name="status"
						label="是否启用"
						initialValue="1"
						rules={[
							{
								required: true,
								message: "请填写是否启用",
							},
						]}
					>
						<Select options={statusOptions} allowClear />
					</Form.Item>
					<Form.Item name="remark" label="备注">
						<TextArea />
					</Form.Item>
				</Form>
			</Drawer>
		</>
	);
}
